package hos.net.soap.convert

import com.drake.net.convert.NetConverter
import com.drake.net.exception.ConvertException
import com.drake.net.exception.RequestParamsException
import com.drake.net.exception.ServerResponseException
import okhttp3.Response
import java.lang.reflect.Type

/**
 * <p>Title: SoapConvert </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-04-09 20:26
 * @version : 1.0
 */
abstract class ResponseConvert : NetConverter {
    override fun <R> onConvert(succeed: Type, response: Response): R? {
        try {
            return NetConverter.onConvert<R>(succeed, response)
        } catch (e: ConvertException) {
            val code = response.code
            when {
                code in 200..299 -> { // 请求成功
                    return response.parseResponse<R>(succeed)
                }
                code in 400..499 -> throw RequestParamsException(
                    response,
                    code.toString()
                ) // 请求参数错误
                code >= 500 -> throw ServerResponseException(response, code.toString()) // 服务器异常错误
                else -> throw ConvertException(
                    response,
                    message = "Http status code not within range"
                )
            }
        }
    }

    /**
     * 解析Response
     *
     * @param succeed JSON对象的类型
     * @receiver Response
     */
    abstract fun <R> Response.parseResponse(succeed: Type): R?
}